package com.dongjiantong.app.controller.quarantine;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.service.EarMarkLifeReadeService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.quarantine.enums.DjtButcherAdmissionInspectionsStatus;
import com.dongjiantong.quarantine.model.DjtButcherAdmissionInspections;
import com.dongjiantong.quarantine.serviceImpl.BreedReportsFileReadService;
import com.dongjiantong.quarantine.serviceImpl.DjtButcherAdmissionInspectionsReadService;
import com.dongjiantong.quarantine.serviceImpl.DjtButcherAdmissionInspectionsWriteService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 15/11/17.
 *
 */
@Slf4j
@OpenBean
public class DjtButcherAdmissionInspectionsController {

    @Reference(version = "1.0.0")
    private DjtButcherAdmissionInspectionsReadService djtButcherAdmissionInspectionsReadService;

    @Reference(version = "1.0.0")
    private DjtButcherAdmissionInspectionsWriteService djtButcherAdmissionInspectionsWriteService;

    @Reference(version = "1.0.0")
    private BreedReportsFileReadService breedReportsFileReadService;

    @Reference(version = "1.0.0")
    private EarMarkLifeReadeService earMarkLifeReadeService;


    /**
     * 查询单据详情 根据 单据 ID
     * @param id 主键 ID
     * @return Response<DjtButcherAdmissionInspections>
     */
    @OpenMethod(
            key = "find.butcher.admission.inspection.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public Response<DjtButcherAdmissionInspections> findById(Long id){
        if(id == null){
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(),HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }

        try{
            DjtButcherAdmissionInspections djtButcherAdmissionInspections = djtButcherAdmissionInspectionsReadService.findById(id);
            //get files
            Map<String , Object> map = Maps.newHashMap();
            map.put("field","quarantine_cert_photo_list");
            map.put("type1", ReportType.ADMISSION_INSPECTION.value());
            map.put("type2",1);
            map.put("relevanceId",djtButcherAdmissionInspections.getId());
            List<String> quarantine_cert_photo_list = breedReportsFileReadService.findListByType(map);
            djtButcherAdmissionInspections.setQuarantine_cert_photo_list(quarantine_cert_photo_list);
            //get ear numbers
            map.clear();
            map.put("reportId",id);
            map.put("reportType",ReportType.ADMISSION_INSPECTION.value());
            List<String> ear_tag_numbers = earMarkLifeReadeService.findListByBreedReportId(map);
            djtButcherAdmissionInspections.setEar_tag_numbers(ear_tag_numbers);
            map.put("isSelected",1);
            List<String> remainder_ears = earMarkLifeReadeService.findListByBreedReportId(map);
            djtButcherAdmissionInspections.setRemainder_ears(remainder_ears);
            return Response.ok(djtButcherAdmissionInspections);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 屠宰端的选择查询
     * @param pageNum 页码
     * @param pageSize 每页多少条
     * @param butcherFarmId 是否被选择
     * @return Response<PageInfo<DjtButcherAdmissionInspections>>
     */
    @OpenMethod(
            key = "paging.butcher.admission.inspection.for.butcher",
            paramNames = {"pageNum","pageSize","butcherFarmId"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtButcherAdmissionInspections>> pagingForButcher(Integer pageNum,
                                                                               Integer pageSize,
                                                                               Long butcherFarmId){
        if(butcherFarmId == null){
            throw new OPServerException(HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getCode(),HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getMessage());
        }
        Map<String , Object> map = Maps.newHashMap();
        map.put("butcherFarmId",butcherFarmId);
        map.put("butcherSelected", 1);
        map.put("status", DjtButcherAdmissionInspectionsStatus.EFFECTIVE.value());
        try{
            PageInfo<DjtButcherAdmissionInspections> djtButcherAdmissionInspectionsPageInfo = djtButcherAdmissionInspectionsReadService.pagingForButcher(pageNum,pageSize,map);
            return Response.ok(djtButcherAdmissionInspectionsPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * 政府端的分页查询
     * @param pageNum 页码
     * @param pageSize 每页多少条
     * @param fromDate 从日期
     * @param toDate 到日期
     * @param butcherSelected 是否被选择
     * @param butcherFarmId 屠宰场id
     * @return Response<PageInfo<DjtButcherAdmissionInspections>>
     */
    @OpenMethod(
            key = "paging.butcher.admission.inspection.for.gov",
            paramNames = {"pageNum","pageSize","fromDate","toDate","butcherSelected","butcherFarmId"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtButcherAdmissionInspections>> pagingForGOV(Integer pageNum,
                                                                           Integer pageSize,
                                                                           String fromDate,
                                                                           String toDate,
                                                                           Integer butcherSelected,
                                                                           Long butcherFarmId){
        Date start = Strings.isNullOrEmpty(fromDate) ? null : DateTime.parse(fromDate).toDate();
        Date end = Strings.isNullOrEmpty(toDate) ? null : DateTime.parse(toDate).toDate();
//        if(butcherSelected == null){
//            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(),HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
//        }
        Map<String , Object> map = Maps.newHashMap();
        if(butcherSelected != null) map.put("butcherSelected",butcherSelected);
        if(start != null) map.put("start",start);
        if(start != null) map.put("end",end);
        List<Long> butcherFarmIds = new ArrayList<Long>();
        if(butcherFarmId != null) {
            butcherFarmIds.add(butcherFarmId);
        }else {
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            butcherFarmIds = loginInfo.getButcherFactoryIds();
        }
        map.put("butcherFarmIds",butcherFarmIds);
        try{
            PageInfo<DjtButcherAdmissionInspections> butcherAdmissionInspectionsPageInfo = djtButcherAdmissionInspectionsReadService.pagingForGOV(pageNum,pageSize,map);
            return Response.ok(butcherAdmissionInspectionsPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 创建单据
     * @param djtButcherAdmissionInspections 单据对象
     * @param toStatus 到状态
     * @return Response<Map<String , Object>>
     */
    @Transactional
    @OpenMethod(
            key = "create.butcher.admission.inspection",
            paramNames = {"djtButcherAdmissionInspections","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String , Object>> create(DjtButcherAdmissionInspections djtButcherAdmissionInspections, Integer toStatus){

        try{
            Date date = new Date();
            LoginInfo loginInfo =  UserUtil.getCurrentUser();
            djtButcherAdmissionInspections.setCreated_at(date);
            djtButcherAdmissionInspections.setUpdated_at(date);
            djtButcherAdmissionInspections.setDelete_flag(1);
            return Response.ok(djtButcherAdmissionInspectionsWriteService.create(djtButcherAdmissionInspections,toStatus,loginInfo));
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.DATA_CREATE_FAIL.getCode(),HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 跟新单据
     * @param djtButcherAdmissionInspections 单据对象
     * @param toStatus 到状态
     * @return Response<Map<String , Object>>
     */
    @Transactional
    @OpenMethod(
            key = "update.butcher.admission.inspection",
            paramNames = {"djtButcherAdmissionInspections","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String , Object>> update(DjtButcherAdmissionInspections djtButcherAdmissionInspections, Integer toStatus){

        if(djtButcherAdmissionInspections.getId() == null){
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(),HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }
        Date date = new Date();
        LoginInfo loginInfo = UserUtil.getCurrentUser();
        djtButcherAdmissionInspections.setUpdated_at(date);
        djtButcherAdmissionInspections.setDelete_flag(1);
        try{
            Integer status = djtButcherAdmissionInspectionsReadService.findStatusById(djtButcherAdmissionInspections.getId());
            if(status != null && !status.equals(djtButcherAdmissionInspections.getStatus().intValue())){
                throw new OPServerException(HttpCode.DOCUMENT_REPEAT_SUBMIT.getCode(),HttpCode.DOCUMENT_REPEAT_SUBMIT.getMessage());
            }
            return Response.ok(djtButcherAdmissionInspectionsWriteService.update(djtButcherAdmissionInspections,toStatus,loginInfo));
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.DATA_UPDATE_FAIL.getCode(),HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }
}
